package com.github.lee.core.common


import android.content.Context
import android.os.Environment
import java.io.File


/**获取语音目录*/
fun getVoiceDir(context: Context): File {
    val storageState = Environment.getExternalStorageState()
    return if (storageState == Environment.MEDIA_MOUNTED) {
        val voiceFilesDir = context.getExternalFilesDir("voice")
        return if (null == voiceFilesDir) {
            File(context.filesDir, "voice")
        } else {
            File(voiceFilesDir.absolutePath)
        }
    } else {
        LogUtil.w("The external storage can not use...")
        File(context.filesDir, "voice")
    }
}

/**获取磁盘缓存图片目录*/
fun getImageCacheDir(context: Context): File {
    val storageState = Environment.getExternalStorageState()
    val dir = if (storageState == Environment.MEDIA_MOUNTED) {
        val cacheDir = context.externalCacheDir
        if (null == cacheDir) {
            File(context.cacheDir, "images")
        } else {
            File(cacheDir, "images")
        }
    } else {
        LogUtil.w("The external storage can not use...")
        File(context.cacheDir, "images")
    }
    if (!dir.exists() || !dir.isDirectory) {
        if (!dir.mkdirs()) {
            throw IllegalAccessException("Can not create folder at ${dir.absolutePath}")
        }
    }
    return dir
}

/**获取磁盘缓存图片目录*/
fun getPhotoDir(context: Context): File {
    val storageState = Environment.getExternalStorageState()
    return if (storageState == Environment.MEDIA_MOUNTED) {
        val pictureDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return pictureDir ?: File(context.filesDir, "Pictures")
    } else {
        LogUtil.w("The external storage can not use...")
        File(context.filesDir, "Pictures")
    }
}

/**获取文件夹大小*/
fun getDirSize(rootDir: File): Long {
    if (rootDir.isDirectory) {
        var size = 0L
        val files = rootDir.listFiles()
        if (files.isNullOrEmpty()) {
            return 0L
        }
        for (item in files) {
            size += if (item.isDirectory) {
                getDirSize(item)
            } else {
                item.length()
            }
        }
        return size
    } else {
        return rootDir.length()
    }

}

fun deleteDir(rootDir: File) {
    if (rootDir.isDirectory) {
        val files = rootDir.listFiles()
        if (files.isNullOrEmpty()) {
            rootDir.delete()
            return
        }
        for (item in files) {
            deleteDir(item)
        }
        //删除文件夹本身
        rootDir.delete()
    } else {
        rootDir.delete()
    }
}